package com.echatim.demo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.echatim.sdk.EChatIMSDKBridge;
import com.echatim.sdk.IPfuncApiCb;
import com.echatim.sdk.IPfuncInitCb;
import com.echatim.sdk.IPfuncListenerCb;
import com.echatim.sdk.IPfuncUploadListenerCb;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  echatim sdk 安卓版
 *  第三方库的标准输出(stdout,stderr)重定向到/sdcard/echatimsdklog/ 目录下, 框架出现问题时可以查看该目录log
 *
 * */
public class MainActivity extends AppCompatActivity {
    private  final String LOG_TAG = MainActivity.class.getName();
    private  boolean sdkInitFinished = false;
    private  int apiCallId = 1; // api 调用id, 实现方式可用时间戳, 或一个自增变量
    private  final int FILE_REQUEST_CODE = 100;


    private static final Map<String, List<String>> TEST_APIS_MAP = new HashMap<String, List<String>>()
    {{
       put("给IM用户发送消息", new ArrayList<String>(){{add("sendMessage");add("{\"body\":{\"body\":\"12345\"},\"fromUser\":\"admin\",\"toTarget\":\"user_1584422783691\",\"type\":\"TEXT\",\"way\":\"P2P\"}");}});
       put("获取用户信息", new ArrayList<String>(){{add("userGet");add("{\"auid\":\"admin\"}");}});
       put("更新用户", new ArrayList<String>(){{add("userUpdate");add("{\"auid\":\"user_1584422783691\",\"avatar\":\"http://www.baidu.com\",\"birth\":\"2020-12-31\",\"email\":\"aa@qq.com\",\"ex\":\"data\",\"gender\":0,\"mobile\":\"13800138000\",\"name\":\"张三\",\"sign\":\"张三的签名\"}");}});
       put("用户列表", new ArrayList<String>(){{add("userList");add("{\"auids\":[\"admin\"]}");}});
       put("更新用户Token", new ArrayList<String>(){{add("userUpdateToken");add("{\"auid\":\"user_1584422783691\",\"token\":\"123456\"}");}});
       put("刷新用户Token", new ArrayList<String>(){{add("userRefreshToken");add("{\"auid\":\"user_1584422783691\"}");}});
       put("获取用户历史信息", new ArrayList<String>(){{add("historyListMessage");add("{\"endTimestamp\":1599702645000,\"fromUser\":\"admin\",\"limit\":10,\"startTimestamp\":0,\"toTarget\":\"user_1584422783691\",\"way\":\"P2P\"}");}});
       put("获取用户历史会话", new ArrayList<String>(){{add("historyListSession");add("{\"auid\":\"admin\",\"endTimestamp\":1599702645000,\"startTimestamp\":0}");}});
       put("添加朋友", new ArrayList<String>(){{add("addFriend");add("{\"alias\":\"好友A\",\"applyText\":\"直接添加好友，我是XXX\",\"auid\":\"admin\",\"targetAuid\":\"user_1584422783691\",\"type\":\"ADD\"}");}});
       put("删除朋友", new ArrayList<String>(){{add("delFriend");add("{\"auid\":\"admin\",\"targetAuid\":\"user_1584422783691\"}");}});
       put("获取朋友列表", new ArrayList<String>(){{add("listFriends");add("{\"auid\":\"admin\",\"updatetime\":0}");}});
       put("获取好友", new ArrayList<String>(){{add("getFriend");add("{\"auid\":\"admin\",\"targetAuid\":\"user_1584422783691\"}");}});
       put("修改朋友黑名单/禁言", new ArrayList<String>(){{add("modifyBlacklistForbid");add("{\"auid\":\"admin\",\"targetAuid\":\"user_1584422783691\",\"type\":\"ADD_BLACKLIST\"}");}});
       put("获取朋友黑名单/禁言列表", new ArrayList<String>(){{add("listBlackListForbid");add("{\"auid\":\"admin\"}");}});
       put("修改朋友别名", new ArrayList<String>(){{add("modifyAlias");add("{\"alias\":\"昵称X\",\"auid\":\"admin\",\"targetAuid\":\"user_1584422783691\"}");}});
       put("添加群", new ArrayList<String>(){{add("addRoom");add("{\"announce\":\"公告\",\"avatar\":\"http://www.baidu.com\",\"confBeinvite\":\"\",\"confInviteother\":\"\",\"confJoinmode\":\"\",\"confUpdate\":\"\",\"introduce\":\"群的简介\",\"inviteText\":\"邀请文字\",\"maxMember\":100,\"members\":[\"user_1584422783691\"],\"name\":\"ui新建的群\",\"owner\":\"admin\"}");}});
       put("更新群", new ArrayList<String>(){{add("updateRoom");add("{\"announce\":\"公告\",\"avatar\":\"http://www.baidu.com\",\"confBeinvite\":\"\",\"confInviteother\":\"\",\"confJoinmode\":\"\",\"confUpdate\":\"\",\"introduce\":\"简介\",\"maxMember\":100,\"name\":\"ui新建的群\",\"owner\":\"admin\",\"rid\":22}");}});
       put("获取群列表", new ArrayList<String>(){{add("listRoom");add("{\"rids\":[22]}");}});
       put("获取用户加入的群", new ArrayList<String>(){{add("listRoomJoin");add("{\"auid\":\"admin\"}");}});
       put("删除群", new ArrayList<String>(){{add("delRoom");add("{\"owner\":\"admin\",\"rid\":22}");}});
       put("获取单个群信息", new ArrayList<String>(){{add("getRoom");add("{\"rid\":22}");}});
       put("列出群成员", new ArrayList<String>(){{add("listRoomMember");add("{\"rids\":[22]}");}});
       put("添加群成员", new ArrayList<String>(){{add("addRoomMember");add("{\"ex\":\"附加参数\",\"inviteText\":\"邀请你进群\",\"members\":[\"admin_1585295718288\"],\"needAgree\":0,\"owner\":\"admin\",\"rid\":22}");}});
       put("删除群成员", new ArrayList<String>(){{add("delRoomMember");add("{\"ex\":\"踢出群附加信息\",\"members\":[\"admin_1585295718288\"],\"owner\":\"admin\",\"rid\":22}");}});
       put("列出用户的在线状态", new ArrayList<String>(){{add("userOnline");add("{\"auids\":[\"admin\"]}");}});
    }};


    private Button connectButton;
    private Button sendButton;
    private Button fileButton;
    private Button uploadButton;
    private Button clearButton;
    private Spinner apiSelector;
    private EditText sdkConfigTextEdit;
    private EditText filePathTextEdit;
    private EditText msgContentTextEdit;
    private EditText apiFormTextEdit;

    private ArrayAdapter<String> apiSelectorAdapter;
    private List<String> valueSelected = new ArrayList<>();
    private String uploadFilePath;
    private Activity activityRef;
    private long fileHandleId = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        connectButton = findViewById(R.id.connectButton);
        sendButton = findViewById(R.id.sendButton);
        fileButton = findViewById(R.id.fileButton);
        uploadButton = findViewById(R.id.uploadButton);
        clearButton = findViewById(R.id.clearButton);
        apiSelector = findViewById(R.id.apiSelector);
        sdkConfigTextEdit = findViewById(R.id.sdkConfigTextEdit);
        filePathTextEdit = findViewById(R.id.filePathTextEdit);
        msgContentTextEdit = findViewById(R.id.msgContentTextEdit);
        apiFormTextEdit = findViewById(R.id.apiFormTextEdit);

        sdkConfigTextEdit.setText("{\"host\":\"api.echatim.cn\",\"httpPort\":58082,\"socketPort\":59092,\"key\":\"TSDKTEST00001\",\"secret\":\"\",\"apiTransport\":\"HTTP\",\"loginAuid\":\"admin\",\"loginToken\":\"admin\",\"fileServerConfig\":{\"use\":\"local\",\"client\":\"curl\",\"baseUrl\":\"http://api.echatim.cn:58082\",\"version\":\"v1\"}}");

        // init Spinner data
        List<String> list = new ArrayList<>();
        list.add("请选择");
        list.addAll(TEST_APIS_MAP.keySet());
        apiSelectorAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
        apiSelectorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        apiSelector.setAdapter(apiSelectorAdapter);

        connectButton.setOnClickListener((v)->{
            final String configJson = sdkConfigTextEdit.getText().toString();
            EChatIMSDKBridge.sdkInit(configJson, sdkInitCb, sdkListenerCb);
            EChatIMSDKBridge.sdkSetApiListener(sdkApiCb);
        });
        sendButton.setOnClickListener((v)->{
            if(valueSelected.isEmpty()){
                Toast.makeText(MainActivity.this, "not select any api", Toast.LENGTH_SHORT).show();
                return;
            }
            String method = valueSelected.get(0);
            String postJson = valueSelected.get(1);
            EChatIMSDKBridge.sdkInvokeApi(apiCallId++, method, postJson);
        });
        fileButton.setOnClickListener((v)->{
            pickFile();
        });
        uploadButton.setOnClickListener((v)->{
            if(this.uploadFilePath == null){
                System.out.println(" uploadFilePath is empty.");
                return;
            }
            System.out.println(String.format("===> ready upload file:%s ", this.uploadFilePath));
            if(fileHandleId == 0){
                System.out.println("file server not init yet.");
                return;
            }
            final int subThread = 0;
            new Thread(()->{
                EChatIMSDKBridge.sdkFileServerInvokeUpload(fileHandleId, this.uploadFilePath, subThread);
            }).start();
        });
        clearButton.setOnClickListener((v)->{
            msgContentTextEdit.setText("");
        });
        apiSelector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String key =  apiSelectorAdapter.getItem(position);
                if(TEST_APIS_MAP.containsKey(key)){
                    valueSelected = TEST_APIS_MAP.get(key);
                    apiFormTextEdit.setText(valueSelected.get(1));
                }
                else {
                    apiFormTextEdit.setText("");
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        sendButton.setEnabled(false);
        fileButton.setEnabled(false);
        uploadButton.setEnabled(false);

        activityRef = this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityRef = null;
    }


    // 打开系统的文件选择器
    private void pickFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
//        intent.setType("*/*");
        intent.setType("file/*");
        this.startActivityForResult(intent, FILE_REQUEST_CODE);
    }

    // 获取文件的真实路径
    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, @Nullable final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            // 用户未选择任何文件，直接返回
            return;
        }
        if(requestCode != FILE_REQUEST_CODE){
            return;
        }
        String filePath = data.getData().getPath();
        // 保存上传文件的路径
        this.uploadFilePath = filePath;
        this.filePathTextEdit.setText(filePath);
        System.out.println(String.format(" ===> select file:%s ", this.uploadFilePath));
    }


    private void appendConsoleText(final String text){
        activityRef.runOnUiThread(()->{
            EditText editText = ((MainActivity)activityRef).msgContentTextEdit;
            editText.setText(editText.getText() + "" + text);
        });
    }


    private IPfuncUploadListenerCb sdkUploadListenerCb = (handleId, method, argv) -> {
        System.out.println(String.format("fileserver upload listener: 0x%x, method: %s, argv[0]:%s, argv[1]:%s", handleId, method, argv[0], argv[1]));
        appendConsoleText(String.format("fileserver upload listener: 0x%x, method: %s, argv[0]:%s, argv[1]:%s", handleId, method, argv[0], argv[1]));
    };

    private IPfuncInitCb sdkInitCb = (ret, errMsg) -> {
        Log.v(LOG_TAG, "sdkInit ok.");
        appendConsoleText("sdkInit ok.");
        if(ret == 0){
            sdkInitFinished = true;

            long handleId =  EChatIMSDKBridge.sdkFileServerInstance();
            if(handleId == 0){
                System.err.println("couldn't instance fileserver");
                appendConsoleText("couldn't instance fileserver");
                return;
            }
            String UPLOAD_CONFIG = "{\"maxFileSize\":100,\"allowSuffix\":[\"jpeg\",\"zip\",\"mp3\"],\"type\":\"FILE\"}";
            EChatIMSDKBridge.sdkFileServerInit(handleId, UPLOAD_CONFIG);
            EChatIMSDKBridge.sdkFileServerSetUploadListener(handleId, sdkUploadListenerCb);

            if(activityRef == null){
                return;
            }
            fileHandleId = handleId;

            activityRef.runOnUiThread(()->{
                ((MainActivity)activityRef).connectButton.setEnabled(false);
                ((MainActivity)activityRef).sendButton.setEnabled(true);
                ((MainActivity)activityRef).fileButton.setEnabled(true);
                ((MainActivity)activityRef).uploadButton.setEnabled(true);
            });
        }
    };



    private IPfuncListenerCb sdkListenerCb = (msg, argv) -> {
        if(!"".equals(msg) && argv.length > 0){
            Log.v(LOG_TAG, String.format("sdk_listener_callback_handler: message = %s, argv[0]=%s", msg, argv[0]));
            appendConsoleText(String.format("sdk_listener_callback_handler: message = %s, argv[0]=%s", msg, argv[0]));
        }
    };

    private IPfuncApiCb sdkApiCb = (int callId, String method, String response) -> {
        if(!"".equals(method)){
            Log.v(LOG_TAG, String.format("api_listener_callback_handler: callId = %d,  method = %s, response = %s", callId, method, response));
            appendConsoleText(String.format("api_listener_callback_handler: callId = %d,  method = %s, response = %s", callId, method, response));
        }
    };


}
